package cn.barudisshu.aspect.transaction;

import cn.barudisshu.Transaction;
import cn.barudisshu.TransactionAdapter;
import cn.barudisshu.TransactionAnn;
import cn.barudisshu.aspect.Aspect;
import cn.barudisshu.exception.TransactionException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author Barudisshu
 */
public class TransactionAspect implements Aspect {

    public Object aspect(InvocationHandler ih, Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;

        TransactionAnn transactionAnn = method.getAnnotation(TransactionAnn.class);
        if (transactionAnn != null) {
            Transaction transaction = new TransactionAdapter();

            // TODO: 获取注解信息或设置值
            String[] names = transactionAnn.name();
            String values = transactionAnn.value();
            int[] level = transactionAnn.level();
            boolean[] readOnly = transactionAnn.readonly();

            try {

                //执行操作
                result = ih.invoke(proxy, method, args);

                // TODO: 处理
                transaction.open();
                transaction.commit();
            }catch (Throwable t) {

                // if exception
                transaction.rollBack();

                Throwable cause = t.getCause();
                if (cause != null) {
                    // you should define your own Exception here
                    throw new TransactionException(cause.getMessage(), cause);
                } else {
                    throw new TransactionException(t.getMessage(), t);
                }

            }finally {
                // finally
                transaction.closeIfStillOpen();
            }
        } else {
            //执行操作
            result = ih.invoke(proxy, method, args);
        }
        return result;
    }

}
